package com.func.infrastructure.persistent.repository;

import cn.bugstack.middleware.db.router.strategy.IDBRouterStrategy;
import com.alibaba.fastjson.JSON;
import com.func.domain.rebate.model.aggerate.BehaviorRebateAggregate;
import com.func.domain.rebate.model.entity.BehaviorRebateOrderEntity;
import com.func.domain.rebate.model.entity.TaskEntity;
import com.func.domain.rebate.model.valobj.BehaviorTypeVO;
import com.func.domain.rebate.model.valobj.DailyBehaviorRebateTypeVO;
import com.func.domain.rebate.repository.IBehaviorRebateRepository;
import com.func.infrastructure.event.EventPublisher;
import com.func.infrastructure.persistent.dao.rebate.IDailyBehaviorRebateDao;
import com.func.infrastructure.persistent.dao.rebate.IUserBehaviorRebateOrderDao;
import com.func.infrastructure.persistent.dao.task.ITaskDao;
import com.func.infrastructure.persistent.po.rebate.DailyBehaviorRebate;
import com.func.infrastructure.persistent.po.rebate.UserBehaviorRebateOrder;
import com.func.infrastructure.persistent.po.task.Task;
import com.func.types.enums.ResponseCode;
import com.func.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * RebateRepository
 * </p>
 *
 * @author Simon
 * @version 2025.03.17.1.0.0
 * @description
 * @since 2025-03-17
 */

@Slf4j
@Repository
public class BehaviorRebateRepository implements IBehaviorRebateRepository {
    @Resource
    private IDailyBehaviorRebateDao dailyBehaviorRebateDao;
    @Resource
    private IUserBehaviorRebateOrderDao userBehaviorRebateOrderDao;
    @Resource
    private ITaskDao taskDao;
    @Resource
    private EventPublisher eventPublisher;
    @Resource
    private IDBRouterStrategy dbRouter;
    @Resource
    private TransactionTemplate transactionTemplate;

    @Override
    public List<DailyBehaviorRebateTypeVO> queryDailyBehaviorRebateConfig(BehaviorTypeVO behaviorTypeVO) {
        List<DailyBehaviorRebate> dailyBehaviorRebates = dailyBehaviorRebateDao.queryDailyBehaviorRebateConfig(behaviorTypeVO.getCode());
        List<DailyBehaviorRebateTypeVO> dailyBehaviorRebateTypeVOS = new ArrayList<>(dailyBehaviorRebates.size());
        for (DailyBehaviorRebate dailyBehaviorRebate : dailyBehaviorRebates) {
            dailyBehaviorRebateTypeVOS.add(DailyBehaviorRebateTypeVO.builder()
                    .rebateDesc(dailyBehaviorRebate.getRebateDesc())
                    .config(dailyBehaviorRebate.getRebateConfig())
                    .RebateType(dailyBehaviorRebate.getRebateType())
                    .behaviorType(dailyBehaviorRebate.getBehaviorType())
                    .build());
        }
        return dailyBehaviorRebateTypeVOS;
    }

    @Override
    public void saveUserRebateRecord(String userId, List<BehaviorRebateAggregate> behaviorRebateAggregates) {
        try {
            dbRouter.doRouter(userId);
            transactionTemplate.execute(status -> {
                try {
                    for (BehaviorRebateAggregate behaviorRebateAggregate : behaviorRebateAggregates) {
                        BehaviorRebateOrderEntity behaviorRebateOrderEntity = behaviorRebateAggregate.getBehaviorRebateOrderEntity();

                        // 用户行为返利订单对象
                        UserBehaviorRebateOrder userBehaviorRebateOrder = new UserBehaviorRebateOrder();
                        userBehaviorRebateOrder.setUserId(behaviorRebateOrderEntity.getUserId());
                        userBehaviorRebateOrder.setOrderId(behaviorRebateOrderEntity.getOrderId());
                        userBehaviorRebateOrder.setBehaviorType(behaviorRebateOrderEntity.getBehaviorType());
                        userBehaviorRebateOrder.setRebateDesc(behaviorRebateOrderEntity.getRebateDesc());
                        userBehaviorRebateOrder.setRebateType(behaviorRebateOrderEntity.getRebateType());
                        userBehaviorRebateOrder.setRebateConfig(behaviorRebateOrderEntity.getRebateConfig());
                        userBehaviorRebateOrder.setBizId(behaviorRebateOrderEntity.getBizId());
                        userBehaviorRebateOrder.setOutBusinessNo(behaviorRebateOrderEntity.getOutBusinessNo());

                        userBehaviorRebateOrderDao.insert(userBehaviorRebateOrder);

                        // 任务对象
                        TaskEntity taskEntity = behaviorRebateAggregate.getTaskEntity();
                        Task task = new Task();
                        task.setUserId(taskEntity.getUserId());
                        task.setTopic(taskEntity.getTopic());
                        task.setMessageId(taskEntity.getMessageId());
                        task.setMessage(JSON.toJSONString(taskEntity.getMessage()));
                        task.setState(taskEntity.getState().getCode());
                        taskDao.insert(task);
                    }
                    return 1;
                } catch (DuplicateKeyException e){
                    status.setRollbackOnly();
                    log.error("写入返利记录, 唯一索引冲突 userId: {}", userId, e);
                    throw new AppException(ResponseCode.INDEX_DUP.getCode(), ResponseCode.INDEX_DUP.getInfo());
                }
            });
        } finally {
            dbRouter.clear();
        }

        // 同步发送MQ消息
        for (BehaviorRebateAggregate behaviorRebateAggregate : behaviorRebateAggregates) {
            TaskEntity taskEntity = behaviorRebateAggregate.getTaskEntity();
            Task task = new Task();
            task.setUserId(taskEntity.getUserId());
            task.setMessageId(taskEntity.getMessageId());
            try {
                // 发送消息 [在事务外执行, 但是失败了有任务补偿]
                eventPublisher.publish(taskEntity.getTopic(), taskEntity.getMessage());
                // 更新数据库记录, task任务表
                taskDao.updateTaskSendMessageCompleted(task);
            } catch (Exception e) {
                log.error("写入返利记录, 发送MQ消息失败 userId: {} topic: {}", userId, task.getTopic());
                taskDao.updateTaskSendMessageFail(task);
            }
        }
    }

    @Override
    public List<BehaviorRebateOrderEntity> queryOrderByOutBusinessNo(String userId, String outBusinessNo) {
        // 1. 请求对象
        UserBehaviorRebateOrder userBehaviorRebateOrder = new UserBehaviorRebateOrder();
        userBehaviorRebateOrder.setUserId(userId);
        userBehaviorRebateOrder.setBizId(outBusinessNo);
        userBehaviorRebateOrder.setBehaviorType(BehaviorTypeVO.SIGN.getCode());

        // 2. 查询结果
        List<UserBehaviorRebateOrder> userBehaviorRebateOrders = userBehaviorRebateOrderDao.queryOrderByOutBusinessNo(userBehaviorRebateOrder);
        List<BehaviorRebateOrderEntity> behaviorRebateOrderEntities = new ArrayList<>(userBehaviorRebateOrders.size());
        for (UserBehaviorRebateOrder behaviorRebateOrder : userBehaviorRebateOrders) {
            BehaviorRebateOrderEntity behaviorRebateOrderEntity = BehaviorRebateOrderEntity.builder()
                        .userId(behaviorRebateOrder.getUserId())
                        .orderId(behaviorRebateOrder.getOrderId())
                        .behaviorType(behaviorRebateOrder.getBehaviorType())
                        .rebateDesc(behaviorRebateOrder.getRebateDesc())
                        .rebateType(behaviorRebateOrder.getRebateType())
                        .rebateConfig(behaviorRebateOrder.getRebateConfig())
                        .outBusinessNo(behaviorRebateOrder.getOutBusinessNo())
                        .bizId(behaviorRebateOrder.getBizId())
                        .build();
            behaviorRebateOrderEntities.add(behaviorRebateOrderEntity);
        }
        return behaviorRebateOrderEntities;
    }
}
